package com.yiyingcanfeng.ping;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.yiyingcanfeng.ping.view.ClearableEditText;


import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class IPQueryActivity extends AppCompatActivity implements View.OnClickListener {

    private ClearableEditText etIp;
    private Button btnQuery;
    private Button btnReset;
    private TextView tvMsg;

    private RequestQueue queue;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_ipquery);
        initView();
        setTitle("IP查询");

        queue = Volley.newRequestQueue(this);
        StringRequest queryCurrentIpRequest = new StringRequest("http://ip138.com/ips1388.asp", new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                try {
                    String s = new String(response.getBytes(StandardCharsets.ISO_8859_1), "gb2312");
                    final String currentIP = s.substring(s.indexOf("：[") + 2, s.lastIndexOf(']'));

                    StringRequest queryCurrentIPInfo = new StringRequest(String.format("http://ip138.com/ips1388.asp?ip=%s&action=2", currentIP), new Response.Listener<String>() {
                        @Override
                        public void onResponse(String response) {
                            try {
                                String s = new String(response.getBytes(StandardCharsets.ISO_8859_1), "gb2312");
                                Pattern pattern = Pattern.compile("本站数据：(.*?)</li>");
                                Matcher matcher = pattern.matcher(s);
                                while(matcher.find()){
                                    String ipInfo = matcher.group(1);
                                    tvMsg.setText(String.format("当前IP:%s\nIP信息:%s", currentIP, ipInfo));
                                }
                            } catch (UnsupportedEncodingException e) {
                                e.printStackTrace();
                            }
                        }
                    }, errorListener);
                    queue.add(queryCurrentIPInfo);
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }

            }
        }, errorListener) {
            @Override
            public Map<String, String> getHeaders() {
                Map<String, String> headers = new HashMap<>();
                headers.put("Host", "ip138.com");
                headers.put("User-Agent", "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36");

                return headers;
            }
        };
        queue.add(queryCurrentIpRequest);
    }

    private void initView() {
        etIp = findViewById(R.id.et_ip);
        btnQuery = findViewById(R.id.btn_query);
        btnQuery.setOnClickListener(this);
        btnReset = findViewById(R.id.btn_reset);
        btnReset.setOnClickListener(this);
        tvMsg = findViewById(R.id.tv_msg);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            default:
                break;
            case R.id.btn_query:
                tvMsg.setText("");
                final String ip = etIp.getText().toString();
                StringRequest queryIPInfoRequest = new StringRequest(String.format("http://ip138.com/ips1388.asp?ip=%s&action=2", ip), new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        try {
                            String s = new String(response.getBytes(StandardCharsets.ISO_8859_1), "gb2312");
                            Pattern pattern = Pattern.compile("本站数据：(.*?)</li>");
                            Matcher matcher = pattern.matcher(s);
                            while(matcher.find()){
                                String ipInfo = matcher.group(1);
                                tvMsg.setText(String.format("IP:%s\nIP信息:%s", ip, ipInfo));
                            }
                        } catch (UnsupportedEncodingException e) {
                            e.printStackTrace();
                        }
                    }
                }, errorListener);
                queue.add(queryIPInfoRequest);
                break;
            case R.id.btn_reset:
                etIp.setText("");
                break;
        }
    }

    Response.ErrorListener errorListener = new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            Log.e("VolleyError", "" + error.getMessage());
        }
    };
}
